package com.travel.anu.controller;

import com.alibaba.fastjson.JSONObject;
import com.travel.anu.model.User;
import com.travel.anu.service.UserService;
import com.travel.anu.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yinyin
 * @create 2021/08/14 下午 4:55
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public JSONObject login(User user, HttpServletRequest request, HttpServletResponse response){
        //判断登录的用户
        if(user.getUserType()==null){
            //默认登录为普通用户
            user.setUserType("user");
        }
        //登录成功
        if(userService.login(user)!=null){
            //当前登录的用户信息存放在session中
            request.getSession().setAttribute("username",user.getUserName());
            //cookie 设置cookie保存用户信息
            Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId());
            cookie.setMaxAge(10*60);
            response.addCookie(cookie);
            //把成功的信息返回
            return JsonResult.sendSuccess();

        }else{
            return JsonResult.sendError();
        }


    }
}
